import React, { Fragment, PureComponent } from 'react';
import { connect } from 'dva';
import {
  Tag,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Icon,
  Input,
  Row,
  Select,
  Modal,
  Dropdown,
  Menu,
} from 'antd';
import TableList from '@/components/TableList';
import Add from './Database/add';
import Edit from './Database/edit';
import styles from '../search.less';
import { isArray } from 'lodash';

const FormItem = Form.Item;
const { Option } = Select;
/* eslint react/no-multi-comp:0 */
@connect(
  state => ({
    loadingqueryPageList: state.loading.effects['database/queryPageList'],
    loadingqueryListByTypeCode: state.loading.effects['database/queryListByTypeCode'],
    dataqueryPageList: state.database.dataqueryPageList,
  }),
  dispatch => ({
    queryPageList: e => dispatch({ type: 'database/queryPageList', payload: e }),
    scan: e => dispatch({ type: 'database/scan', payload: e }),
    dbinfodelete: e => dispatch({ type: 'database/dbinfodelete', payload: e }),
    testConnection: e => dispatch({ type: 'database/testConnection', payload: e }),
    updateLevel: e => dispatch({ type: 'database/updateLevel', payload: e }),
    queryListByTypeCode: e => dispatch({ type: 'database/queryListByTypeCode', payload: e }),
  })
)
@Form.create()
class database extends PureComponent {
  state = {
    selectedRows: [],
    datadbType: [],
  };

  columns = [
    {
      title: '数据库名',
      dataIndex: 'dbName',
    },
    {
      title: '待扫描数据库名',
      dataIndex: 'needScanDb',
    },
    {
      title: '数据库类型',
      dataIndex: 'dbType',
    },
    {
      title: 'IP地址',
      dataIndex: 'dbIp',
    },
    {
      title: '端口',
      dataIndex: 'dbPort',
    },
    {
      title: '实例名',
      dataIndex: 'serviceName',
    },
    {
      title: '用户名',
      dataIndex: 'dbAccount',
    },
    {
      title: '操作',
      width: 220,
      render: text => (
        <>
          <a
            onClick={() =>
              Modal.confirm({
                title: '扫描',
                content: '您确定要扫描吗？',
                okText: '扫描',
                cancelText: '取消',
                onOk: () =>
                  this.props.scan({ dbId: text.dbId }).then(res => {
                    if (res.result == 'ok') {
                      Modal.success({ title: res.msg });
                    } else {
                      Modal.error({ title: '操作失败', content: res.msg });
                    }
                  }),
              })
            }
          >
            扫描
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.testConnection(text.dbId)}>测试连接</a>

          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={() => this.updateLevel(text.dbId)}>更新分级分类</a>
                </Menu.Item>
                <Menu.Item>
                  <Edit pageList={this.pageList} text={text}>
                    编辑
                  </Edit>
                </Menu.Item>
                <Menu.Item>
                  <a onClick={() => this.deleteData(text.dbId)}>删除</a>
                </Menu.Item>
              </Menu>
            }
          >
            <a>
              更多
              <Icon type="down" />
            </a>
          </Dropdown>
        </>
      ),
    },
  ];

  testConnection = id => {
    Modal.confirm({
      title: '测试连接',
      content: '您确定要测试这个数据库吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () =>
        this.props.testConnection({ dbId: id }).then(res => {
          if (res.result == 'ok') {
            Modal.success({ title: res.msg });
          } else {
            Modal.error({ title: '操作失败', content: res.msg });
          }
        }),
    });
  };

  //更新分级分类
  updateLevel = id => {
    Modal.confirm({
      title: '更新分级分类',
      content: (
        <span>
          更新分类分级结果，此过程将持续3-5分钟。
          <br />
          您确定要更新吗？
        </span>
      ),
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleUpdateLevel(id),
    });
  };

  handleUpdateLevel(id) {
    const { dispatch } = this.props;
    const values = { dbId: id };
    // this.props.updateLevel(values);
    return this.props.updateLevel(values).then(res => {
      if (res.result == 'ok') {
        Modal.success({ title: res.msg });
        this.pageList();
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    });
  }

  //删除
  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  // 删除方法
  handleDeleteData(id) {
    const values = {
      dbIds: isArray(id) ? id.join(',') : id,
    };
    return this.props.dbinfodelete(values).then(res => {
      if (res.result == 'ok') {
        Modal.success({ title: res.msg });
        this.pageList();
        this.setState({ selectedRows: [] });
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    });
  }
  componentDidMount() {
    this.pageList();
    this.props.queryListByTypeCode({ dataDictTypeCode: 'dbType' }).then(res => {
      if (res.rescode == 200) {
        this.setState({ datadbType: res.data ? res.data.dataList || [] : [] });
      } else {
        Modal.error({ title: '获取数据库类型失败' });
      }
    });
  }

  // 分页查询列表
  pageList = (res, pageSize = 10, pageNum = 0) => {
    const values = {
      ...this.state.formValues,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    this.props.queryPageList(values);
  };

  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.dbId),
    });
  };
  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState(
        {
          formValues: values,
        },
        this.pageList
      );
    });
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="数据库名">
              {getFieldDecorator('dbName')(<Input allowClear placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="数据库类型">
              {getFieldDecorator('dbType')(
                <Select placeholder="请选择" allowClear>
                  <Option value="">全部</Option>
                  {this.state.datadbType.map(item => (
                    <Option value={item.value} key={item.value}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { selectedRows } = this.state;
    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Add pageList={this.pageList}>
              <Button icon="plus" type="primary">
                新增
              </Button>
            </Add>
            {selectedRows.length > 0 && (
              <span>
                <Button onClick={() => this.deleteData(selectedRows)}>批量删除</Button>
              </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={this.props.loadingqueryPageList}
            data={this.props.dataqueryPageList}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.dbId}
            // hideRowSelection
          />
        </div>
      </Card>
    );
  }
}
export default database;
